package com.migrate.module.migrate;

import com.migrate.module.config.ApplicationContextUtil;
import com.migrate.module.domain.EtlProgressConfig;
import com.migrate.module.mapper.migrate.MigrateScrollMapper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 加载数据配置信息
 *
 * @author zhonghuashishan
 */
@Component
public class MergeConfig {

    /**
     *  存储用来校验匹配的字段,每个表维护一个集合
     */
    private static final Map<String, List<String>> FIELD_MAP = new HashMap<>();

    /**
     *  存储每个表设定的唯一字段
     */
    private static final Map<String, String> RECORD_KEY_MAP = new HashMap<>();


    @PostConstruct
    public void init(){
        MigrateScrollMapper migrateScrollMapper = ApplicationContextUtil.getBean(MigrateScrollMapper.class);
        // 获取所有的配置
        List<EtlProgressConfig> etlProgressConfigList = migrateScrollMapper.queryEtlProgressConfigList();
        // 按表名先进行分组
        Map<String, List<EtlProgressConfig>> etlProgressConfigMap = etlProgressConfigList.stream().collect(Collectors.groupingBy(EtlProgressConfig::getLogicModel));

        // 封装数据写入配置的对象内，提供方法对外获取
        for (Map.Entry<String,List<EtlProgressConfig>> entry:etlProgressConfigMap.entrySet()){
            // 单个表的配置
            List<EtlProgressConfig> progressConfigList = entry.getValue();
            List<String> queryCheckKeyList = new ArrayList<>();
            for (EtlProgressConfig etlProgressConfig:progressConfigList){
                // 获取到每个表配置的唯一字段
                if (etlProgressConfig.getRecordType().equals(0)){
                    String recordKey = etlProgressConfig.getRecordKey();
                    RECORD_KEY_MAP.put(entry.getKey(), recordKey);
                } else {
                    queryCheckKeyList.add(etlProgressConfig.getRecordKey());
                }
            }
            FIELD_MAP.put(entry.getKey(), queryCheckKeyList);
        }
    }

    /**
     * 获取表的指定唯一字段
     * @param tableName 表名
     * @return 指定的唯一字段
     */
    public static String getSingleKey(String tableName){
        if (RECORD_KEY_MAP.containsKey(tableName)){
            return RECORD_KEY_MAP.get(tableName);
        }
        return "";
    }

    /**
     *  获取配置的匹配字段
     * @param key 配置关键字段
     * @return 匹配字段
     */
    public static List<String> getFiledKey(String key){
        if (FIELD_MAP.containsKey(key)){
            return FIELD_MAP.get(key);
        }
        return new ArrayList<>();
    }

}
